import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
  useRef,
} from 'react';
import {
  Table,
  Modal,
  Space,
  Button,
  Input,
  Form,
  message,
  Menu,
  Dropdown,
  Empty,
} from 'antd';
import { PlusOutlined, DeleteOutlined, DownOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { deepClone, InbizIcon } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import { EditableRow, EditableCell } from './editTable';
import { checkBind } from '../services';
import ModelPicker from './ModelPicker';
import PagePicker from './PagePicker';
import { reduction } from './utils';
import styles from '../index.less';

// 生成随机字符串
const random = (): string => {
  const s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
  let l = s.length;
  let n = '';
  for (let i = 1; i < 30; i++) {
    if (i % 6 || !i) {
      n += s.charAt(Math.floor(Math.random() * l));
    } else {
      n += '-';
    }
  }
  return n;
};

// 内置动作数据
const actionSelfData = [
  {
    id: '_add',
    name: 'PermissionConfig.builtin_add',
    value: 'add',
  },
  {
    id: '_edit',
    name: 'PermissionConfig.builtin_edit',
    value: 'edit',
  },
  {
    id: '_delete',
    name: 'PermissionConfig.builtin_delete',
    value: 'delete',
  },
  {
    id: '_select',
    name: 'PermissionConfig.builtin_query',
    value: 'select',
  },
];

const EditableContext = React.createContext<FormInstance<any> | null>(null);

export { EditableContext };

interface DataType {
  id: React.Key;
  value: string;
  name: string;
}

type EditableTableProps = Parameters<typeof Table>[0];

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

const PaneAction = (props: any) => {
  // 动作数据列表
  const [actionList, $actionList] = useState<object[]>([]);
  // 动作分组列表
  const [actionGroupList, $actionGroupList] = useState<any[]>([]);
  // 内置动作列表（赛选后）
  const [actionSelfList, $actionSelfList] = useState<any[]>([]);
  // 选中的key
  const [selectedRowKeys, $selectedRowKeys] = useState<string[]>([]);
  // 内置动作选中的key
  const [selectedSelfRowKeys, $selectedSelfRowKeys] = useState<string[]>([]);
  // 内置动作modal显示
  const [actionSelfVisible, $actionSelfVisible] = useState<boolean>(false);
  // 添加分组自定义modal显示
  const [addGroupVisible, $addGroupVisible] = useState<boolean>(false);
  // 添加分组模型modal显示
  const [addGroupModelVisible, $addGroupModelVisible] =
    useState<boolean>(false);
  // 添加子页面modal显示
  const [pageVisible, $pageVisible] = useState<boolean>(false);
  // 当前选中分组
  const [activeGroup, $activeGroup] = useState<string>('');
  // 当前选中页面
  const [activePage, $activePage] = useState<string>('');
  // 当前内置动作选中个数
  const [selectedTotal, $selectedTotal] = useState<number>(0);
  // 当前模型选中个数
  const [selectedModelTotal, $selectedModelTotal] = useState<number>(0);
  // 当前子页面选中个数
  const [selectedPageTotal, $selectedPageTotal] = useState<number>(0);
  // 可修改表格当前key
  const [nowKey, $nowKey] = useState(null);
  // 回填模型列表选中数据
  const [setSelect, $setSelect] = useState<string[]>([]);
  // 子页面检测接口调用loadding
  const [loadding, $loadding] = useState<boolean>(false);
  // 子页面数据
  const [pageList, $pageList] = useState<any[]>([]);
  // 子页面是否展开选中页面tag列表
  const [showTag, $showTag] = useState<boolean>(false);

  // 动作数据(字符串化)
  const actionDataRef = useRef<string>();
  // 模型选择提交方法绑定
  const modelPickerRef = useRef<any>();
  // 页面选择提交方法绑定
  const pagePickerRef = useRef<any>();

  // 添加分组表单
  const [form] = Form.useForm();
  // 可修改表格表单
  const [formEdit] = Form.useForm();

  const { appInfo } = props;

  // 向上暴露校验表格表单方法
  useImperativeHandle(
    props.refs,
    () => ({
      submit: submit,
    }),
    [activeGroup, actionList, pageList, actionGroupList],
  );

  // 处理内置动作数据
  const nzData = useMemo(() => {
    let data = [...actionSelfData];
    let list: any[] = [];
    data.map((item) => {
      list.push({
        id: `${activeGroup}${item.id}_nz`,
        name: item.name,
        value: item.value,
      });
    });
    return list;
  }, [activeGroup]);

  // 同步更新子页面列表数据
  useEffect(() => {
    if (props.pageData?.length) {
      const arr = deepClone(props.pageData);
      $pageList(arr);
      initShow(arr);
    }
  }, [props.pageData]);

  // 添加一条空数据动作
  const dataAdd = useCallback(() => {
    let arr = [...actionList];
    arr.push({
      id: random(),
      name: '',
      value: '',
    });
    $actionList(arr);
  }, [actionList]);

  // 删除选中模型
  const dataDel = useCallback(() => {
    let arr = [...actionList];
    selectedRowKeys.map((item) => {
      arr = arr.filter((val: any) => val.id !== item);
    });
    $actionList(arr);
    $selectedRowKeys([]);
  }, [actionList, selectedRowKeys]);

  // 确定-添加内置动作
  const actionSelfSubmit = useCallback(() => {
    let arr = [...actionList];
    selectedSelfRowKeys.map((item) => {
      let fil = actionList.filter((val: any) => val.id === item);
      if (!fil.length) {
        let filData = nzData.filter((val: any) => val.id === item);
        arr.push(...filData);
      }
    });
    $actionList(arr);
    $selectedSelfRowKeys([]);
    $selectedTotal(0);
    $actionSelfVisible(false);
  }, [selectedSelfRowKeys, actionList]);

  // 新建分组
  const addGroup = () => {
    form.resetFields();
    $addGroupVisible(true);
  };

  // 确定-添加分组
  const addGroupSubmit = useCallback(() => {
    form.validateFields().then((res: any) => {
      let name = res.name;
      let fil = actionGroupList.filter((item) => item.name === name);
      if (fil.length) {
        message.warning(getMessage('PermissionConfig.message_duplicate_group')); // 分组已存在
        return;
      }
      let obj: any = {
        type: 'custom',
        tag: res.tag,
        name: name,
        parentOutId: activePage,
        list: [],
      };
      let none = !actionGroupList.length;
      $actionGroupList([...actionGroupList, obj]);
      actionDataRef.current = String([...actionGroupList, obj]);
      none && $activeGroup(obj.tag);
      $addGroupVisible(false);
    });
  }, [actionGroupList, activePage]);

  // 选中页面
  const setActivePage = useCallback(
    (tag: string, newList?: any[]) => {
      // px1：如果之前选中过分组则触发表单校验并保存在分组下的动作列表list中
      if (activeGroup !== '') {
        let actionData: any[] = [...actionList];
        // px1.1:非空判断
        let record: any = null;
        for (let i = 0; i < actionData.length; i++) {
          if (actionData[i].name === '' || actionData[i].value === '') {
            record = actionData[i];
            break;
          }
        }
        if (!record) {
          // px1.1.1~1：循环遍历判断是否有重复value值
          let valueArr: string[] = [];
          let nameArr: string[] = [];
          let cf: boolean = false;
          for (let i = 0; i < actionData.length; i++) {
            if (valueArr.indexOf(actionData[i].value) >= 0) {
              message.warning(
                getMessage('PermissionConfig.message_duplicate_value'),
              ); // 值不能重复
              cf = true;
              break;
            }
            // if (nameArr.indexOf(actionData[i].name) >= 0) {
            //   message.warning(getMessage('PermissionConfig.message_duplicate_name')); // 名称不能重复
            //   cf = true;
            //   break;
            // }
            valueArr.push(actionData[i].value);
            nameArr.push(actionData[i].name);
          }
          if (cf) {
            return;
          }
          // px1.1.1~2：保存动作列表到分组下
          let groupData = [...actionGroupList];
          for (let i = 0; i < groupData.length; i++) {
            if (groupData[i].tag === activeGroup) {
              groupData[i].list = [...actionData];
              break;
            }
          }
          let list = newList ? newList : [...pageList];
          let newActionGroupList: any[] = [];
          list.map((item: any) => {
            if (
              item.OutId === activePage ||
              (item.OutId === props.value.pageOutId &&
                activePage === '' &&
                groupData.length)
            ) {
              item.list = groupData;
            }
            if (item.OutId === tag && item.list) {
              newActionGroupList = item.list;
            }
          });
          $pageList(list);
          $activePage(tag);
          $actionGroupList(newActionGroupList);
          if (newActionGroupList.length) {
            // 如果还剩下分组，自动选中第一个及回填该分组下的动作列表
            $activeGroup(newActionGroupList[0].tag);
            if (newActionGroupList[0].list) {
              $actionList(newActionGroupList[0].list);
            } else {
              $actionList([]);
            }
          } else {
            $activeGroup('');
            $actionList([]);
          }
        } else {
          // px1.1.2:触发空值处校验
          let type = record.name === '' ? 'name' : 'value';
          document.getElementById(`cell-${type}-${record.id}`)?.click();
          setTimeout(() => {
            formEdit.validateFields();
          });
        }
      } else {
        let list = newList ? newList : [...pageList];
        let newActionGroupList: any[] = [...actionGroupList];
        // px1.2：回填新分组下动作列表
        list.map((item: any) => {
          if (
            item.OutId === activePage ||
            (item.OutId === props.value.pageOutId && activePage === '')
          ) {
            if (item.list && item.list.length && activePage !== '')
              item.list = [];
          }
          if (
            (item.OutId === tag ||
              (item.OutId === props.value.pageOutId && activePage === '')) &&
            item.list
          ) {
            newActionGroupList = item.list;
          }
        });
        $pageList(list);
        $activePage(tag);
        $actionGroupList(newActionGroupList);
        if (newActionGroupList.length) {
          // 如果还剩下分组，自动选中第一个及回填该分组下的动作列表
          $activeGroup(newActionGroupList[0].tag);
          if (newActionGroupList[0].list) {
            $actionList(newActionGroupList[0].list);
          } else {
            $actionList([]);
          }
        } else {
          $activeGroup('');
          $actionList([]);
        }
      }
    },
    [
      activePage,
      activeGroup,
      actionList,
      actionGroupList,
      pageList,
      props.value.pageOutId,
    ],
  );

  // 选中分组
  const setActive = useCallback(
    (tag) => {
      // px1：如果之前选中过分组则触发表单校验并保存在分组下的动作列表list中
      if (activeGroup !== '') {
        let actionData: any[] = [...actionList];
        // px1.1:非空判断
        let record: any = null;
        for (let i = 0; i < actionData.length; i++) {
          if (actionData[i].name === '' || actionData[i].value === '') {
            record = actionData[i];
            break;
          }
        }
        if (!record) {
          // px1.1.1~1：循环遍历判断是否有重复value值
          let valueArr: string[] = [];
          let nameArr: string[] = [];
          let cf: boolean = false;
          for (let i = 0; i < actionData.length; i++) {
            if (valueArr.indexOf(actionData[i].value) >= 0) {
              message.warning(
                getMessage('PermissionConfig.message_duplicate_value'),
              ); // 值不能重复
              cf = true;
              break;
            }
            // if (nameArr.indexOf(actionData[i].name) >= 0) {
            //   message.warning(getMessage('PermissionConfig.message_duplicate_name')); // 名称不能重复
            //   cf = true;
            //   break;
            // }
            valueArr.push(actionData[i].value);
            nameArr.push(actionData[i].name);
          }
          if (cf) {
            return;
          }
          // px1.1.1~2：保存动作列表到分组下
          let groupData = [...actionGroupList];
          for (let i = 0; i < groupData.length; i++) {
            if (groupData[i].tag === activeGroup) {
              groupData[i].list = [...actionData];
              break;
            }
          }
          $actionGroupList(groupData);
          actionDataRef.current = String(groupData);
          // px1.1.1~3：回填新分组下动作列表
          let list = [];
          for (let i = 0; i < actionGroupList.length; i++) {
            if (actionGroupList[i].tag === tag) {
              list = actionGroupList[i].list;
              break;
            }
          }
          $actionList(list);
          $activeGroup(tag);
        } else {
          // px1.1.2:触发空值处校验
          let type = record.name === '' ? 'name' : 'value';
          document.getElementById(`cell-${type}-${record.id}`)?.click();
          setTimeout(() => {
            formEdit.validateFields();
          });
        }
      } else {
        // px1.2：回填新分组下动作列表
        let list = [];
        for (let i = 0; i < actionGroupList.length; i++) {
          if (actionGroupList[i].tag === tag) {
            list = actionGroupList[i].list;
            break;
          }
        }
        $actionList(list);
        $activeGroup(tag);
      }
    },
    [activeGroup, actionList, actionGroupList],
  );

  // 处理回显
  const initShow = useCallback(
    (list: any[]) => {
      setActivePage('', list);
    },
    [setActivePage],
  );

  // 删除分组
  const delGroupItem = useCallback(
    (tag) => {
      let arr = actionGroupList.filter((item: any) => item.tag !== tag);
      $actionGroupList(arr);
      actionDataRef.current = String(arr);
      if (activeGroup === tag) {
        // 如果还剩下分组，自动选中第一个及回填该分组下的动作列表
        if (arr.length) {
          $activeGroup(arr[0].tag);
          $actionList(arr[0].list);
        } else {
          $activeGroup('');
          $actionList([]);
        }
      }
    },
    [actionGroupList, activeGroup],
  );

  // 删除子页面
  const delGroupPage = useCallback(
    (OutId) => {
      let arr = pageList.filter((item: any) => item.OutId !== OutId);
      $pageList(arr);
      $activePage(props.value.pageOutId || '');
      if (activePage === OutId) {
        if (arr.length) {
          $activePage(arr[0].OutId);
          let newActionGroupList = arr[0].list || [];
          $actionGroupList(newActionGroupList);
          if (newActionGroupList.length) {
            // 如果还剩下分组，自动选中第一个及回填该分组下的动作列表
            $activeGroup(newActionGroupList[0].tag);
            if (newActionGroupList[0].list) {
              $actionList(newActionGroupList[0].list);
            } else {
              $actionList([]);
            }
          } else {
            $activeGroup('');
            $actionList([]);
          }
        } else {
          $activePage(props?.value?.pageOutId || '');
          $activeGroup('');
          $actionGroupList([]);
          $actionList([]);
        }
      }
    },
    [pageList, activePage, props.value.route, props.value.pageOutId],
  );

  // 触发表单校验
  const submit = useCallback(() => {
    let actionData: any[] = [...actionList];
    // px1.1:非空判断
    let record: any = null;
    for (let i = 0; i < actionData.length; i++) {
      if (actionData[i].name === '' || actionData[i].value === '') {
        record = actionData[i];
        break;
      }
    }
    if (!record) {
      // px1.1.1~1：循环遍历判断是否有重复value值
      let valueArr: string[] = [];
      let nameArr: string[] = [];
      let cf: boolean = false;
      for (let i = 0; i < actionData.length; i++) {
        if (valueArr.indexOf(actionData[i].value) >= 0) {
          message.warning(
            getMessage('PermissionConfig.message_duplicate_value'),
          ); // 值不能重复
          cf = true;
          break;
        }
        // if (nameArr.indexOf(actionData[i].name) >= 0) {
        //   message.warning(getMessage('PermissionConfig.message_duplicate_name')); // 名称不能重复
        //   cf = true;
        //   break;
        // }
        valueArr.push(actionData[i].value);
        nameArr.push(actionData[i].name);
      }
      if (cf) {
        return;
      }
      // px1.1.1~2：保存动作列表到分组下
      let groupData = [...actionGroupList];
      for (let i = 0; i < groupData.length; i++) {
        if (groupData[i].tag === activeGroup) {
          groupData[i].list = [...actionData];
          break;
        }
      }
      let list = [...pageList];
      list.map((item: any) => {
        if (
          item.OutId === activePage ||
          (item.OutId === props.value.pageOutId &&
            activePage === '' &&
            groupData.length)
        ) {
          item.list = groupData;
        }
      });
      let newList = deepClone(list);
      props?.setPageData?.(newList);
      return newList;
    } else {
      // px1.1.2:触发空值处校验
      let type = record.name === '' ? 'name' : 'value';
      document.getElementById(`cell-${type}-${record.id}`)?.click();
      setTimeout(() => {
        formEdit.validateFields();
      });
      return false;
    }
  }, [
    activePage,
    activeGroup,
    actionList,
    actionGroupList,
    pageList,
    props.value.pageOutId,
  ]);

  // 修改保存刚编辑表格的数据
  const handleSave = (row: DataType) => {
    const newData: DataType[] = [...actionList] as DataType[];
    const index = newData.findIndex((item: any) => row.id === item.id);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    $actionList(newData);
  };

  // 内置动作筛选
  const selfFilter = (e: any) => {
    console.log('sss0', nzData, e.target.value);

    let arr = nzData.filter(
      (item) => getMessage(item.name).indexOf(e.target.value) > -1,
    );
    $actionSelfList(arr);
  };

  // 新建模型分组提交
  const modelSubmit = useCallback(async () => {
    if (modelPickerRef.current && modelPickerRef.current.submit) {
      let data = await modelPickerRef.current.submit();
      if (Array.isArray(data)) {
        let arr: any[] = [];
        data.map((item) => {
          let name = item.Name;
          let fil = actionGroupList.filter((val) => val.name === name);
          if (fil.length) {
            // message.warning(`分组${name}已存在`);
            return;
          }
          let obj: any = {
            type: 'model',
            tag: item.ModelKey,
            name: item.Name,
            parentOutId: activePage,
            list: [],
          };
          arr.push(obj);
        });
        $actionGroupList([...actionGroupList, ...arr]);
        actionDataRef.current = String([...actionGroupList, ...arr]);
        let none = !actionGroupList.length;
        none && arr.length && $activeGroup(arr[0].tag);
        $selectedModelTotal(0);
        $addGroupModelVisible(false);
      }
    }
  }, [actionGroupList, activePage]);

  // 打开模型选择model
  const openModelModal = useCallback(() => {
    const arr = actionGroupList.filter((item) => item.type === 'model');
    let select = arr.map((item) => item.tag);
    $setSelect(select);
    $addGroupModelVisible(true);
  }, [actionGroupList]);

  // 多选配置
  const rowSelection = useMemo(
    () => ({
      selectedRowKeys,
      onChange: (selectedRowKeys: any) => {
        $selectedRowKeys(selectedRowKeys);
      },
    }),
    [selectedRowKeys],
  );

  // 内置动作多选配置
  const rowSelectionSelfChange = useCallback((selectedKeys: any) => {
    $selectedSelfRowKeys(selectedKeys);
    $selectedTotal(selectedKeys.length);
  }, []);

  // 内置动作多选点击行选择/取消
  const rowClick = useCallback(
    (record: any) => {
      if (Array.isArray(selectedSelfRowKeys)) {
        let select = [...selectedSelfRowKeys];
        if (select?.indexOf(record.id) > -1) {
          let idx = select?.indexOf(record.id);
          if (idx || idx === 0) select?.splice(idx, 1);
        } else {
          select.push(record.id);
        }
        $selectedSelfRowKeys(select);
        $selectedTotal(select.length);
      }
    },
    [selectedSelfRowKeys],
  );

  // Title按钮Dom
  const renderTitle = useCallback(() => {
    return (
      <div className={styles['table-title-nav']}>
        <Space size="middle" align="start">
          <Button
            type="primary"
            onClick={dataAdd}
            disabled={activeGroup === ''}
          >
            <TextWidget>PermissionConfig.btn_add</TextWidget> {/* 添加 */}
          </Button>
          <Button onClick={dataDel} disabled={!selectedRowKeys.length} danger>
            <TextWidget>global.delete</TextWidget> {/* 删除 */}
          </Button>
        </Space>
        <Button
          onClick={() => {
            $actionSelfList(nzData);
            $actionSelfVisible(true);
          }}
          disabled={activeGroup === ''}
        >
          <TextWidget>PermissionConfig.built_in_action</TextWidget>{' '}
          {/* 内置动作 */}
        </Button>
      </div>
    );
  }, [dataAdd, dataDel, selectedRowKeys, activeGroup]);

  // 内置动作弹窗footerDOM
  const RederFooter = useCallback(() => {
    return (
      <div className={styles['page-select-model-footer']}>
        <div className={styles['select-count-nav']}>
          <p>
            <TextWidget>PermissionConfig.selected_total</TextWidget>{' '}
            {/* 已选个数 */}： <span>{selectedTotal}</span>
          </p>
        </div>
        <Space>
          <Button
            key="cancel"
            onClick={() => {
              $actionSelfVisible(false);
              $selectedTotal(0);
              $selectedSelfRowKeys([]);
            }}
          >
            <TextWidget>global.cancel</TextWidget> {/* 取消 */}
          </Button>
          <Button key="submit" type="primary" onClick={actionSelfSubmit}>
            <TextWidget>global.sure</TextWidget> {/* 确定 */}
          </Button>
        </Space>
      </div>
    );
  }, [actionSelfSubmit, selectedTotal]);

  // 动作列表表格字段配置
  const actionColumns = [
    {
      title: getMessage('PermissionConfig.title_name'), // 名称
      dataIndex: 'name',
      key: 'name',
      width: '45%',
      editable: true,
    },
    {
      title: getMessage('PermissionConfig.title_value'), // 标识
      dataIndex: 'value',
      key: 'value',
      width: '45%',
      editable: true,
    },
  ];

  // 内置动作表格字段配置
  const actionSelfColumns = [
    {
      title: getMessage('PermissionConfig.title_name'), // 名称
      dataIndex: 'name',
      key: 'name',
      width: 714,
      render: (txt: string) => <TextWidget>{txt}</TextWidget>,
    },
  ];

  // 可修改表格自定义render
  const components = useMemo(() => {
    return {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
  }, []);

  // 可修改表格字段重组
  const columnsed = actionColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        nowKey: nowKey,
        setNowKey: (e: any) => $nowKey(e),
        handleSave: handleSave,
      }),
    };
  });

  // 新建分组选择
  const menu = useMemo(
    () => (
      <Menu
        items={[
          {
            label: (
              <span onClick={openModelModal}>
                <TextWidget>PermissionConfig.menu_model</TextWidget>{' '}
                {/* 模型 */}
              </span>
            ),
            key: '0',
          },
          {
            label: (
              <span onClick={addGroup}>
                <TextWidget>PermissionConfig.menu_custom</TextWidget>{' '}
                {/* 自定义 */}
              </span>
            ),
            key: '1',
          },
        ]}
      />
    ),
    [addGroup, openModelModal],
  );

  // 模型列表弹窗footerDOM
  const RederModelFooter = useCallback(() => {
    return (
      <div className={styles['page-select-model-footer']}>
        <div className={styles['select-count-nav']}>
          <p>
            <TextWidget>PermissionConfig.selected_total</TextWidget>{' '}
            {/* 已选个数 */}： <span>{selectedModelTotal}</span>
          </p>
        </div>
        <Space>
          <Button
            key="cancel"
            onClick={() => {
              $addGroupModelVisible(false);
              $selectedModelTotal(0);
            }}
          >
            <TextWidget>global.cancel</TextWidget> {/* 取消 */}
          </Button>
          <Button key="submit" type="primary" onClick={modelSubmit}>
            <TextWidget>global.sure</TextWidget> {/* 确定 */}
          </Button>
        </Space>
      </div>
    );
  }, [modelSubmit, selectedModelTotal]);

  // 更新选中总数
  const editTotal = (num: number) => {
    $selectedPageTotal(num);
  };

  // 提交添加的页面
  const modelPageSubmit = async () => {
    if (pagePickerRef.current && pagePickerRef.current.submit) {
      $loadding(true);
      let data = await pagePickerRef.current.submit();
      let pageOutIds = data.map((item: any) => item.OutId);
      if (!pageOutIds.length) {
        $loadding(false);
        $pageVisible(false);
        $showTag(false);
        return;
      }
      checkBind(appInfo, props.value.pageOutId, pageOutIds)
        .then((res) => {
          if (Array.isArray(res) && res.length) {
            let list = [...pageList];
            res.map((item: any) => {
              let arr = pageList.filter((val: any) => val.OutId === item.OutId);
              if (!arr.length) {
                let data = reduction(item);
                data && list.push(data);
              }
            });
            $pageList(list);
            $loadding(false);
            $pageVisible(false);
            $showTag(false);
          } else {
            $loadding(false);
          }
        })
        .catch(() => {
          $loadding(false);
        });
    }
  };

  // 子页面弹窗footerDOM
  const PageRederFooter = useCallback(() => {
    return (
      <div className={styles['page-select-model-footer']}>
        <div className={styles['select-count-nav']}>
          <p>
            <TextWidget>PermissionConfig.selected_total</TextWidget>{' '}
            {/* 已选个数 */}：<span>{selectedPageTotal}</span>&nbsp;&nbsp;
            <DownOutlined
              onClick={() => $showTag(!showTag)}
              style={
                showTag
                  ? { transform: 'scaleY(.8) rotate(180deg)' }
                  : { transform: 'scaleY(.8) rotate(0)' }
              }
            />
          </p>
        </div>
        <Space>
          <Button
            key="cancel"
            onClick={() => {
              $pageVisible(false);
              $showTag(false);
            }}
          >
            <TextWidget>global.cancel</TextWidget> {/* 取消 */}
          </Button>
          <Button key="submit" type="primary" onClick={modelPageSubmit}>
            <TextWidget>global.sure</TextWidget> {/* 确定 */}
          </Button>
        </Space>
      </div>
    );
  }, [selectedPageTotal, showTag]);

  return (
    <>
      <div className={styles['pane-action']}>
        <div
          className={`${styles['left-content']} ${styles['left-content-page']}`}
        >
          <div className={styles['left-content-title']}>
            <span>
              <TextWidget>PermissionConfig.subpage</TextWidget> {/* 子页面 */}
            </span>
            <div
              onClick={() => {
                $pageVisible(true);
                $selectedPageTotal(0);
              }}
            >
              <a
                style={{
                  color: 'var(--inbiz-color-primary)',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                <PlusOutlined />
                <span style={{ fontSize: '14px' }}>
                  &nbsp;
                  <TextWidget>PermissionConfig.btn_add</TextWidget> {/* 添加 */}
                </span>
              </a>
            </div>
          </div>
          <div className={styles['left-content-list']}>
            <div
              className={
                activePage === props.value.pageOutId || activePage === ''
                  ? `${styles['left-content-list-page']} ${styles['left-content-list-item-active']}`
                  : styles['left-content-list-page']
              }
              onClick={() => setActivePage(props?.value?.pageOutId || '')}
            >
              <span title={getMessage(props?.value?.pageName)}><TextWidget>{props?.value?.pageName}</TextWidget></span>
            </div>
            {pageList
              .filter((val: any) => val.OutId !== props.value.pageOutId)
              .map((item: any) => {
                return (
                  <div
                    className={
                      item.OutId === activePage
                        ? `${styles['left-content-list-item']} ${styles['left-content-list-item-active']}`
                        : styles['left-content-list-item']
                    }
                    key={item.OutId}
                    onClick={() => {
                      setActivePage(item.OutId);
                    }}
                  >
                    <span title={getMessage(item.Name)}>
                      <TextWidget>{item.Name}</TextWidget>
                    </span>
                    <div
                      onClick={(e) => {
                        e.stopPropagation();
                        delGroupPage(item.OutId);
                      }}
                    >
                      <DeleteOutlined />
                    </div>
                  </div>
                );
              })}
          </div>
        </div>
        <div className={styles['left-content']}>
          <div className={styles['left-content-title']}>
            <span>
              <TextWidget>PermissionConfig.group</TextWidget> {/* 分组 */}
            </span>
            <div>
              <Dropdown
                overlay={menu}
                trigger={['click']}
                overlayClassName={styles['pane-action-dropdown']}
              >
                <a
                  onClick={(e) => e.preventDefault()}
                  style={{
                    color: 'var(--inbiz-color-primary)',
                    display: 'flex',
                    alignItems: 'center',
                  }}
                >
                  <PlusOutlined />
                  <span style={{ fontSize: '14px' }}>
                    &nbsp;
                    <TextWidget>PermissionConfig.btn_new</TextWidget>{' '}
                    {/* 新建 */}
                  </span>
                </a>
              </Dropdown>
            </div>
          </div>
          <div className={styles['left-content-list']}>
            {actionGroupList.map((item: any) => {
              return (
                <div
                  className={
                    item.tag === activeGroup
                      ? `${styles['left-content-list-item']} ${styles['left-content-list-item-active']}`
                      : styles['left-content-list-item']
                  }
                  key={item.tag}
                  onClick={() => {
                    setActive(item.tag);
                  }}
                >
                  <span title={getMessage(item.name)}>
                    <TextWidget>{item.name}</TextWidget>
                  </span>
                  {item.name !== '默认分组' ? (
                    <div
                      onClick={(e) => {
                        e.stopPropagation();
                        delGroupItem(item.tag);
                      }}
                    >
                      <DeleteOutlined />
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        </div>
        <div className={styles['right-content']}>
          <Form form={formEdit} component={false}>
            <EditableContext.Provider value={formEdit}>
              <Table
                title={renderTitle}
                columns={columnsed as ColumnTypes}
                components={components}
                dataSource={actionList}
                rowKey="id"
                bordered
                rowSelection={rowSelection}
                pagination={false}
                scroll={{ y: 300 }}
                locale={{
                  emptyText: (
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description={
                        <TextWidget>PermissionConfig.no_data</TextWidget>
                      }
                    />
                  ),
                }}
              />
            </EditableContext.Provider>
          </Form>
        </div>
      </div>
      {/* 新建分组自定义modal */}
      <Modal
        visible={addGroupVisible}
        width={400}
        title={getMessage('PermissionConfig.modal_title_add_group')} // 添加分组
        onCancel={() => $addGroupVisible(false)}
        onOk={addGroupSubmit}
        okText={getMessage('global.sure')} // 确认
        cancelText={getMessage('global.cancel')} // 取消
        destroyOnClose
      >
        <div className={styles['action-self-nav']}>
          <Form form={form}>
            <br />
            <Form.Item
              name="name"
              label={getMessage('PermissionConfig.title_name')} // 名称
              rules={[
                {
                  required: true,
                  message: getMessage('PermissionConfig.message_no_name'),
                  whitespace: true,
                },
              ]} // 名称不能为空
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="tag"
              label={getMessage('PermissionConfig.title_value')} // 标识
              initialValue={random()}
              rules={[
                {
                  required: true,
                  message: getMessage('PermissionConfig.message_no_value'),
                },
              ]} // 标识不能为空
            >
              <Input disabled />
            </Form.Item>
          </Form>
        </div>
      </Modal>
      {/* 新建分组模型modal */}
      <Modal
        visible={addGroupModelVisible}
        width={800}
        title={getMessage('PermissionConfig.modal_title_pick_model')} // 选择模型
        onCancel={() => {
          $addGroupModelVisible(false);
          $selectedModelTotal(0);
        }}
        destroyOnClose
        footer={[<RederModelFooter key="modelFooter" />]}
      >
        <ModelPicker
          {...props}
          refs={modelPickerRef}
          setTotal={$selectedModelTotal}
          setSelect={setSelect}
        />
      </Modal>
      {/* 内置动作modal */}
      <Modal
        visible={actionSelfVisible}
        width={800}
        title={getMessage('PermissionConfig.modal_title_pick_built_in_action')} // 选择内置动作
        onCancel={() => {
          $actionSelfVisible(false);
          $selectedTotal(0);
          $selectedSelfRowKeys([]);
        }}
        footer={[<RederFooter key="footer" />]}
        destroyOnClose
      >
        <div className={styles['action-self-nav']}>
          <Input
            placeholder={getMessage(
              'PermissionConfig.placeholder_input_key_word',
            )} // 请输入关键词
            onChange={selfFilter}
            allowClear
            suffix={
              <InbizIcon type="icon-ic-sousuo" style={{ color: '#999' }} />
            }
          />
          <Table
            columns={actionSelfColumns}
            dataSource={actionSelfList}
            rowKey="id"
            rowSelection={{
              selectedRowKeys: selectedSelfRowKeys,
              onChange: rowSelectionSelfChange,
            }}
            pagination={false}
            onRow={(record: { id: string }) => {
              return {
                onClick: (e) => {
                  e.stopPropagation();
                  rowClick(record);
                },
              };
            }}
          />
        </div>
      </Modal>
      {/* 添加子页面modal */}
      <Modal
        visible={pageVisible}
        width={800}
        bodyStyle={{ height: 488 }}
        title={getMessage('PermissionConfig.modal_title_pick_page')} // 页面选择
        onCancel={() => {
          $pageVisible(false);
          $showTag(false);
        }}
        destroyOnClose
        footer={[<PageRederFooter key="footer" />]}
      >
        <PagePicker
          {...props}
          refs={pagePickerRef}
          totalChange={editTotal}
          checkLoading={loadding}
          showTagList={showTag}
        />
      </Modal>
    </>
  );
};

export default PaneAction;
